import React, { useState, useRef } from 'react'
import { IconLock, IconUser } from '@arco-design/web-react/icon'
import './index.css'
import { Form, Input, Link, Button, Space } from '@arco-design/web-react'
import { login } from '../../api/oauth'
import { useDispatch } from 'react-redux'
import { getUserInfo } from '../../store/features/userSlice'
import cache from '../../utils/cache'
import Logo from '@assets/images/logo.png'
import { withRouter } from 'react-router-dom'

function Login(props) {
  const formRef = useRef()
  const dispatch = useDispatch()
  const [loginForm, setLoginForm] = useState({
    grant_type: 'password',
    username: '',
    password: '',
    skipCaptcha: 'y',
    key: '',
    captcha: '',
  })

  const [errorMessage, setErrorMessage] = useState('')
  const [loading, setLoading] = useState(false)

  // 登录成功
  function afterLoginSuccess(token) {
    // 用户信息
    dispatch(getUserInfo())
    // 存token
    cache.setToken(token)
    // 跳转首页
    window.location.href = '/'
  }

  // 登录
  const handleLogin = (params) => {
    // console.log('handleLogin param:', params)
    setErrorMessage('')
    setLoading(true)
    login(params)
      .then((res) => {
        // console.log('handleLogin res:', res)
        // res.access_token
        const { access_token } = res
        if ((access_token !== null) & (access_token !== undefined)) {
          afterLoginSuccess(access_token)
        } else {
          setErrorMessage(res.msg || '登录异常')
        }
      })
      .catch((err) => {
        console.log(err)
        setErrorMessage(JSON.stringify(err))
      })
      .finally(() => {
        setLoading(false)
      })
  }

  // 登录
  function onSubmitClick() {
    formRef.current.validate().then((values) => {
      handleLogin({ ...loginForm, ...values })
    })
  }

  // 注册
  function onRegisterClick() {
    // 跳转首页
    props.history.push('/register')
  }

  return (
    <div className={'login-form-wrapper'}>
      {/* 左边 */}
      <div className='login-form-left'>
        {/* <span>
          <img src={Logo} alt='' style={{ verticalAlign: 'middle', borderStyle: 'none' }} />
        </span> */}
      </div>
      {/* 右边 */}
      <div className='login-form-right'>
        <img src={Logo} alt='' className='login-logo' />

        <Form className={['login-form']} layout='vertical' ref={formRef} initialValues={loginForm}>
          <div className={'login-form-title'}>拖油(ToldU)</div>
          <div className={['login-form-sub-title']}>一款飞书风的即时通讯软件，属于借力好风的闲暇之作。</div>
          <Form.Item field='username' rules={[{ required: true, message: '请输入用户名' }]}>
            <Input size={'large'} prefix={<IconUser />} placeholder={'用户名'} onPressEnter={onSubmitClick} />
          </Form.Item>
          <Form.Item field='password' rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password size={'large'} prefix={<IconLock />} placeholder={'密码'} onPressEnter={onSubmitClick} />
          </Form.Item>
          {/* <div>{errorMessage}</div> */}
          {/* <div>
          <img src={captchaBase64} alt='验证码' onClick={() => getCaptcha()} />
        </div> */}
          <Space size={16} direction='vertical'>
            <div className={['login-form-password-actions']}>
              {/* <Checkbox checked={rememberPassword} onChange={setRememberPassword}>
              {['login.form.rememberPassword']}
            </Checkbox> */}
              {/* <Link>忘记密码</Link> */}
            </div>
            <Button size={'large'} type='primary' long onClick={onSubmitClick} loading={loading}>
              登录
            </Button>
            <Button size={'large'} type='text' long className={['login-form-register-btn']} onClick={onRegisterClick}>
              没有账号？去注册
            </Button>
          </Space>
        </Form>
      </div>
    </div>
  )
}

export default withRouter(Login)
